#include "cwhttprequest.h"

CWHttpRequest::CWHttpRequest(const std::string &request)
{
    size_t index = 0;
    // 解析请求行
    parseRequestRow(request, index);
    // 解析请求头
    parseRequestHeader(request, index);
    // 解析请求体
    m_body = std::string(&request[index], &request[request.size()]);
}

void CWHttpRequest::parseRequestRow(const std::string &request, size_t &index)
{
    size_t pre_index = index;
    while (request[index] != ' ')
        ++index;
    m_method = std::string(&request[pre_index], &request[index]);
    ++index;
    pre_index = index;
    while (request[index] != ' ')
        ++index;
    m_URL = std::string(&request[pre_index], &request[index]);
    ++index;
    pre_index = index;
    while (request.compare(index, 2, "\r\n") != 0)
        ++index;
    m_version = std::string(&request[pre_index], &request[index]);
    index += 2;
}

void CWHttpRequest::parseRequestHeader(const std::string &request, size_t &index)
{
    size_t pre_index = index;
    std::string key, val;
    while (true)
    {
        if (request[index] == ':') // 构造请求头key
        {
            key = std::string(&request[pre_index], &request[index]);
            if (request[index + 1] == ' ')
                index += 2;
            else
                ++index;
            pre_index = index;
        }
        else if (request.compare(index, 2, "\r\n") == 0) // 构造请求头val
        {
            val = std::string(&request[pre_index], &request[index]);
            m_header.emplace(key, val);
            // 检查是否是最后一个请求头
            if (request.compare(index, 4, "\r\n\r\n") == 0)
            {
                index += 4;
                break;
            }
            index += 2;
            pre_index = index;
        }
        else
            ++index;
    }
}

std::string CWHttpRequest::getRequestHeader(const char *key)
{
    if (m_header.count(key) == 0)
        return std::string();
    return m_header.at(key);
}